package com.cooljie.controller;

import com.cooljie.entity.Course;
import com.cooljie.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by ACER on 2017/6/9.
 */
@Controller
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private CourseService courseService;
//查看所有课程信息
    @RequestMapping(value = "/courseList",method = RequestMethod.GET)
    public  String allCourse(Model model){
        List<Course> courseList= courseService.selectAllCourse();
        model.addAttribute("courseList",courseList);
        return "course/courseList";
    }
//更新课程信息
    @RequestMapping(value = "/update",method = RequestMethod.GET)
    public  String updateCourse(HttpServletRequest request,Model model){

        Course course=new Course();
       course.setCourseId(Integer.parseInt(request.getParameter("courseId")));
        course.setCourseCredit(Double.valueOf(request.getParameter("courseCredit")));
        course.setCourseNo(request.getParameter("courseNo"));
        course.setCourseName(request.getParameter("courseName"));
        model.addAttribute("course",course);

        return "course/updateCourse";
    }

    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public  String updateCourse(@Validated Course course){
        courseService.updateCourse(course);
        return "redirect:/course/courseList";
    }

//    添加课程

    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String addCourse(){
        return "course/addCourse";
    }
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public  String addCourse(@Validated Course course){
    courseService.addCourse(course);
    return "redirect:/course/courseList";
}
//    删除课程
    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    public String deleteCourse(HttpServletRequest request){
        try{
            int id= Integer.parseInt(request.getParameter("courseId"));
//        System.out.println(id+">>>");
            courseService.deleteCourse(id);
        }
        catch (NumberFormatException e){
            e.printStackTrace();
        }

        return "redirect:/course/courseList";
    }
}
